SUBROUTINE FREE_REQUESTS &
& (request_send_2d, request_recv_2d, &
&  request_send_3d, request_recv_3d)

! Subroutine FREE_REQUESTS frees the requests of persistent
! communication operations

use MPI_VARIABLES, only : &
& maxshift

implicit none

include 'mpif.h'

! Input/output variables
integer(4), intent(inout) :: request_send_2d(1:8)
integer(4), intent(inout) :: request_recv_2d(1:8)
integer(4), intent(inout) :: request_send_3d(1:maxshift,1:26)
integer(4), intent(inout) :: request_recv_3d(1:maxshift,1:26)

! Local variables and parameters
integer(4) :: i, j, ierr
!integer(4) :: flag
integer(4) :: istatus(1:MPI_STATUS_SIZE)
logical :: flag


do i = 1, 8

!  call MPI_TEST(request_send_2d(i), flag, istatus, ierr)
!  call MPI_REQUEST_GET_STATUS(request_send_2d(i), flag, MPI_STATUS_IGNORE, ierr)
!  if (flag) then
  if (request_send_2d(i) /= MPI_REQUEST_NULL) then
    call MPI_REQUEST_FREE(request_send_2d(i), ierr)
  endif
!  else
!    write(*,*) 'Warning: Persistent MPI communications have not completed!'
!  endif

  if (request_recv_2d(i) /= MPI_REQUEST_NULL) then
!  call MPI_REQUEST_GET_STATUS(request_recv_2d(i), flag, MPI_STATUS_IGNORE, ierr)
!  if (flag) then
    call MPI_REQUEST_FREE(request_recv_2d(i), ierr)
!  else
!    write(*,*) 'Warning: Persistent MPI communications have not completed!'
!  endif
  endif

enddo

do j = 1, 26
  do i = 1, maxshift
    if (request_send_3d(i,j) /= MPI_REQUEST_NULL) then
      call MPI_REQUEST_FREE(request_send_3d(i,j), ierr)
    endif
    if (request_recv_3d(i,j) /= MPI_REQUEST_NULL) then
      call MPI_REQUEST_FREE(request_recv_3d(i,j), ierr)
    endif
  enddo
enddo

END SUBROUTINE FREE_REQUESTS
